#target illustrator
(function () {
    var supportedExtensions = {
        ".ai": true,
        ".ait": true,
        ".eps": true,
        ".pdf": true,
        ".svg": true,
        ".svgz": true
    };

    var sourceFolder = Folder.selectDialog("选择包含 Illustrator 文件的文件夹");
    if (!sourceFolder) { return; }

    var targets = [];
    collectFiles(sourceFolder, targets);

    if (!targets.length) {
        alert("选定的文件夹中没有可处理的文件。");
        return;
    }

    var successCount = 0;
    var failureDetails = [];

    var originalInteraction = app.userInteractionLevel;
    try {
        app.userInteractionLevel = UserInteractionLevel.DONTDISPLAYALERTS;

        for (var i = 0; i < targets.length; i++) {
            var file = targets[i];
            var doc = null;

            try {
                doc = app.open(file); // 使用默认打开方式
                exportAsSVG(doc, file);
                successCount++;
            } catch (err) {
                failureDetails.push(file.fsName + " -> " + err);
            } finally {
                if (doc) {
                    doc.close(SaveOptions.DONOTSAVECHANGES);
                }
            }
        }
    } finally {
        app.userInteractionLevel = originalInteraction;
    }

    var message = "已完成导出。\n成功: " + successCount + " 个文件";
    if (failureDetails.length) {
        message += "\n失败: " + failureDetails.length + " 个文件\n" + failureDetails.join("\n");
    }
    alert(message);

    function collectFiles(folder, list) {
        var entries = folder.getFiles();
        for (var i = 0; i < entries.length; i++) {
            var entry = entries[i];
            if (entry instanceof Folder) {
                collectFiles(entry, list);
            } else if (entry instanceof File && hasSupportedExtension(entry)) {
                list.push(entry);
            }
        }
    }

    function hasSupportedExtension(file) {
        var name = file.displayName || file.name;
        var dotIndex = name.lastIndexOf(".");
        if (dotIndex < 0) { return false; }
        var ext = name.substring(dotIndex).toLowerCase();
        return !!supportedExtensions[ext];
    }

    function exportAsSVG(doc, sourceFile) {
        var exportOptions = new ExportOptionsWebOptimizedSVG();
        exportOptions.compressed = false;
        exportOptions.coordinatePrecision = 3;
        exportOptions.cssProperties = SVGCSSPropertyLocation.PRESENTATIONATTRIBUTES;
        exportOptions.fontSubsetting = SVGFontSubsetting.None;
        exportOptions.fontType = SVGFontType.SVGFONT;
        exportOptions.svgResponsive = false;
        exportOptions.saveMultipleArtboards = true;
        exportOptions.rasterImageLocation = RasterImageLocation.PRESERVE;

        var baseName = decodeURI(sourceFile.displayName || sourceFile.name).replace(/\.[^\.]+$/, "");
        var exportFile = new File(sourceFile.parent.fsName + "/" + baseName + ".svg");
        doc.exportFile(exportFile, ExportType.WOSVG, exportOptions);
    }
})();
